# _*_coding:utf-8 _*_
# @Time　　:2021/3/14 17:31
# @Author　 : wangyong
# @File　　  :conftest.py
# @Software  :PyCharm

from py._xmlgen import html
from time import strftime, time
import pytest
from _pytest import terminal


@pytest.fixture()
def init():
    print("我是初始化操作。。")
    return 10


@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
    cells.insert(1, html.th('描述'))  # 表头添加Description
    cells.insert(4, html.th('执行时间', class_='sortable time', col='time'))
    cells.pop(-1)  # 删除link


@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
    cells.insert(1, html.td(report.description))  #表头对应的内容
    cells.insert(4, html.td(strftime('%Y-%m-%d %H:%M:%S'), class_='col-time'))
    cells.pop(-1)  # 删除link列


@pytest.mark.optionalhook
def pytest_html_results_table_html(report, data):   #清除执行成功的用例logs
    if report.passed:
        del data[:]
        data.append(html.div('pass case not log。', class_='empty log'))


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):  #description取值为用例说明__doc__
    outcome = yield
    report = outcome.get_result()
    report.description = str(item.function.__doc__)


@pytest.mark.optionalhook
def pytest_html_report_title(report):
    report.title = "移动端接口测试报告"


# 修改Environment部分信息，配置测试报告环境信息
def pytest_configure(config):
    # 添加接口地址与项目名称
    config._metadata["项目名称"] = "移动端接口"
    config._metadata['接口地址'] = 'https://m.zxxk.com'
    config._metadata['开始时间'] = strftime('%Y-%m-%d %H:%M:%S')
    # 删除Java_Home
    config._metadata.pop("JAVA_HOME")
    config._metadata.pop("Packages")
    config._metadata.pop("Platform")
    config._metadata.pop("Plugins")
    config._metadata.pop("Python")


# 修改Summary部分的信息
def pytest_html_results_summary(prefix, summary, postfix):
    prefix.extend([html.p("所属部门: 测试运维部")])
    prefix.extend([html.p("测试人员: xy04952")])


def pytest_terminal_summary(terminalreporter, exitstatus, config):

    """收集测试结果"""
    # print(terminalreporter.stats)
    print("total:", terminalreporter._numcollected)
    print('passed:', len([i for i in terminalreporter.stats.get('passed', []) if i.when == 'call']))
    print('failed:', len([i for i in terminalreporter.stats.get('failed', []) if i.when == 'call']))
    print('error:', len([i for i in terminalreporter.stats.get('failed', []) if i.when == 'setup']))
    print('skipped:', len([i for i in terminalreporter.stats.get('skipped', [])]))
    print('成功率：%.2f' % ((len([i for i in terminalreporter.stats.get('passed', []) if i.when == 'call']))/
                        terminalreporter._numcollected*100)+'%')
    duration = time() - terminalreporter._sessionstarttime
    print('total times: %.2f' % duration, 'seconds')
